import { defineStore } from 'pinia'

export const useJsonStore = defineStore('json', {
  state: () => ({
    source: '',
    content: {},
  }),
  actions: {
    // 设置 JSON 内容
    setContent(newContent: object) {
      this.content = newContent
    },
    // 清空 JSON 内容
    clearContent() {
      this.content = {}
    },
    // 设置 source
    setSource(newSource: string) {
      this.source = newSource
    },
    // 清空 source
    clearSource() {
      this.source = ''
    },
    // 解析 source 为 content
    parseSource() {
      try {
        this.content = JSON.parse(this.source)
      }
      catch (error) {
        console.error('解析JSON失败:', error)
        this.content = {}
      }
    },
  },
  getters: {
    // 获取 JSON 内容
    getContent(): object {
      return this.content
    },
    // 获取 source
    getSource(): string {
      return this.source
    },
    // 检查内容是否为空
    isEmpty(): boolean {
      return Object.keys(this.content).length === 0
    },
  },
})
